package cn.kow.kmall.core.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Map;

/**
 * @Author: lijun
 * @Description:
 * @Date: Created in 2019-08-10 15:24
 * @Modified By:
 */
public class JwtTokenUtils {

    /**
     * token 过期时间, 单位: 秒. 这个值表示 30 天
     */
    private static final long TOKEN_EXPIRED_TIME = 24 * 60 * 60;

    /**
     * 创建JWT
     */
    public static String generateToken(String subject, Map<String, Object> claims, String secret, Long time) {
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime nowDate = LocalDateTime.now();
        LocalDateTime expDate = nowDate.plusSeconds(time != null ? time : TOKEN_EXPIRED_TIME);
        byte[] keyBytes = secret.getBytes();
        SecretKey key = Keys.hmacShaKeyFor(keyBytes);
        String jws = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(subject)
                .setClaims(claims)
                .signWith(key)
                .setIssuedAt(Date.from(nowDate.atZone(zoneId).toInstant()))
                .setExpiration(Date.from(expDate.atZone(zoneId).toInstant()))
                .compact();
        return jws;
    }

    /**
     * 验证jwt
     */
    public static Claims verify(String token, String secret) {
        //签名秘钥，和生成的签名的秘钥一模一样
        byte[] keyBytes = secret.getBytes();
        SecretKey key = Keys.hmacShaKeyFor(keyBytes);
        Jws<Claims> jws = Jwts.parser()  //得到DefaultJwtParser
                .setSigningKey(key)         //设置签名的秘钥
                .parseClaimsJws(token);
        Claims claims = jws.getBody();
        return claims;
    }
}
